<?php

/**
 * Created by PhpStorm.
 * User: edmmss
 * Date: 2021/9/28
 * Time: 10:45
 */

namespace Edmmss\Easyswoole\Task\Server;

use Edmmss\Easyswoole\Task\Traits\Singleton;

class Response
{
    use Singleton;

    const RESPONSE_SUCCESS_CODE = 200;

    private $_isSuccess;

    private $_errorCode;

    /**
     * 获取发送成功数据
     *
     * @date   2021/9/28
     * @param $code
     * @param $call
     * @param $data
     * @return array
     * @author edmmss
     */
    public function getSuccessSendData($code, $call, $data)
    {
        $sendData = [
            'code' => $code,
            'call' => $call,
            'data' => $data,
        ];

        return $sendData;
    }

    /**
     * 获取发送失败数据
     *
     * @date   2021/10/1
     * @return array
     * @author edmmss
     */
    public function getErrorSendData()
    {
        // 都是错误消息，就不用给正常数据了
        $sendData = [
            'code'      => $this->_errorCode,
            'call'      => '',
            'data'      => [],
            'errorCode' => $this->_errorCode,
        ];

        return $sendData;
    }

    /**
     * 校验数据
     *
     * @date   2021/10/1
     * @param $originalData
     * @author edmmss
     */
    public function validation($originalData)
    {
        $header = isset($originalData['header']) ? $originalData['header'] : [];
        $data = isset($originalData['data']) ? $originalData['data'] : [];

        $this->_isSuccess = true;
        if (!$header || !$data) {
            $this->_isSuccess = false;
            $this->_errorCode = \Edmmss\Easyswoole\Task\Client\Response::ERR_DATA_PARSE;
        }

        if ($header &&
            (!isset($header['length'])
                || !isset($header['serializerType'])
                || !isset($header['serialId'])
                || !isset($header['id']))) {
            $this->_isSuccess = false;
            $this->_errorCode = \Edmmss\Easyswoole\Task\Client\Response::ERR_DATA_HEADER;
        }

        if ($data &&
            (!isset($data['call'])
                || !isset($data['params'])
                || !isset($data['taskType']))) {
            $this->_isSuccess = false;
            $this->_errorCode = \Edmmss\Easyswoole\Task\Client\Response::ERR_DATA_DATA;
        }
    }

    /**
     * 是否成功
     *
     * @date   2021/10/1
     * @return mixed
     * @author edmmss
     */
    public function isSuccess()
    {
        return $this->_isSuccess;
    }
}